<?php
namespace Kuoqi\Api;
require_once(__DIR__.DIRECTORY_SEPARATOR.'qrcode'.DIRECTORY_SEPARATOR.'qrlib.php');

use Kuoqi\Config;

/**
 * 二维码相关
 * Class Qrcode
 * @package Kuoqi\Api
 * User kuoqi
 * Datetime 2022/4/29 10:09
 * Remark
 */
class Qrcode extends \Kuoqi\Api{

    static $QR_ROOT = '';//配置qrcode的生成路径信息[一般为站点根目录]
    static $QR_TMPROOT = '/runtime/qrcode';//一级缓存文件目录
    static $QR_SERVER = '';//服务地址信息

    public $tmp_path = '';//临时文件夹[距离根目录]
    public $dir = '';//临时DIR路径信息
    public $errorCorrectionLevel = 'H';



    /**
     * 初始化
     * Email constructor.
     */
    public function __construct()
    {
        //初始化配置self::$sconfig = new config;
        self::$QR_ROOT = Config::get('HOME');
        $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
        self::$QR_SERVER = $protocol.$_SERVER['HTTP_HOST'];

        $this->dir = self::$QR_TMPROOT.'/'.date('Ymd');
        is_dir(self::$QR_ROOT.
            '/'
            .$this->dir)||mkdir(self::$QR_ROOT.
            '/'
            .$this->dir,0777,true);
    }

    final function initOptions($options){
        $opts = array(
            'errLevel'=>'H',
            'matrixPointSize'=>4,
            'hasServer'=>true,
        );
        if(is_array($options)){

            if(isset($options['errLevel'])&&in_array($options['errLevel'], array('L','M','Q','H'))){
                ($opts['errLevel'] = $options['errLevel']);
            }

            if(isset($options['matrixPointSize'])){
                $opts['matrixPointSize'] = min(max((int)$options['matrixPointSize'], 1), 10);
            }

            isset($options['hasHost'])&&($opts['hasHost'] = $options['hasHost']);
        }
        return $opts;
    }

    public function show($conts='',$options = array()){
        $options = self::initOptions($options);
        $filename = $this->dir.'/'.md5($conts).'.png';
        \QRcode::png($conts, self::$QR_ROOT.$filename, $options['errLevel'], $options['matrixPointSize'], 2);
        if($options['hasServer']){
            return self::$QR_SERVER.$filename;
        }else{
            return $filename;
        }
    }

}